package com.cy.module.dingtalk.mobility;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.Batch;
import com.cy.model.DeviceAttr;
import com.cy.model.Shift;
import com.cy.module.WebApiController;
import com.cy.utils.dingtalk.DingTalkUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@ControllerBind(controllerKey = "/clmp/dingtalk/mobility/shift")
public class ShiftController extends WebApiController {

    @Override
    public void index() {
    }

    @Override
    public void update() {
        super.update();
    }

    /**
     * 生成班次
     */
    @Override
    public void save() {
        Long batchId = getParaToLong("batch_id");
        Account loginAccount = getLoginAccount();
        Shift shift = new Shift();
        shift.setBatchId(batchId);
        shift.setProductionDate(new Date());
        shift.setStatus(Shift.Status.ENABLED.getValue());
        shift.setRemark(getPara("remark"));
        shift.setOpenerId(loginAccount.getAccountId());
        try {
            shift.save();
            Batch batch = shift.getBatch();
            batch.setStatus(1);
            batch.update();

            DeviceAttr deviceAttr = batch.getDeviceAttr();
            HashMap<String, Object> params = new HashMap<>(4, 1F);
            params.put("shift", shift);
            params.put("batch", batch);
            params.put("opener", loginAccount);
            params.put("deviceAttr", deviceAttr);
            renderStatus(1, params);
        } catch (Exception e) {
            e.printStackTrace();
            renderFail();
        }
    }

    @Override
    public void delete() {
        super.delete();
    }

    /**
     * 开工页面
     */
    public void goProducing(){
        List<DeviceAttr> deviceAttrs = DeviceAttr.dao.findAll();
        JSONArray jsonArray = new JSONArray(deviceAttrs.size());
        for (DeviceAttr deviceAttr : deviceAttrs){
            JSONObject jsonObject = new JSONObject(2, true);
            jsonObject.put("key", deviceAttr.getModelNum());
            jsonObject.put("value", deviceAttr.getId());
            jsonArray.add(jsonObject);
        }
        setAttr("modelItems", jsonArray);
        setAttr("config", DingTalkUtils.getJsapiConfig(getRequest()));
        renderJsp("/view/dingtalk/mobility/Production-producing.jsp");
    }

    public void getBatchByDeviceAttr(){
        renderJson(Batch.dao.findByDeviceAttr(getParaToLong("device_attr_id")));
    }

}